﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.IO;

namespace IBS2ibsImport
{
    public partial class Service1 : ServiceBase
    {
        private Timer timer = null;

        public Service1()
        {
            InitializeComponent();
            try
            {
                if (!EventLog.SourceExists(this.ServiceName + "_log"))
                    EventLog.CreateEventSource(this.ServiceName, this.ServiceName + "_log");
            }
            catch { }
            serviceLog.Source = this.ServiceName + "_log";
            serviceLog.Log = this.ServiceName + "_log";
        }

        protected override void OnStart(string[] args)
        {
            serviceLog.WriteEntry(this.ServiceName + " запущен");
            Properties.Settings.Default.Reload();
            var ExecuteTimes = Properties.Settings.Default.ExecuteTimes;
            if (Properties.Settings.Default.ExecuteImmediately)
                ExecuteTimes.Add(DateTime.Now.AddMinutes(1).ToString("HH:mm"));

            timer = new Timer();
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = TimerUtil.GetNewTimerInterval(ExecuteTimes);
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            serviceLog.WriteEntry(this.ServiceName + " остановлен");
            timer.Stop();
            timer.Close();
        }

        /// <summary>
        /// При срабатывании таймера
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            // Останавливаем таймей и стартуем выполнение выгрузки
            timer.Stop();
            Process();
            // Интервал таймера
            Properties.Settings.Default.Reload();
            timer.Interval = TimerUtil.GetNewTimerInterval(Properties.Settings.Default.ExecuteTimes);
            timer.Start();
        }

        private void Process()
        {
            try
            {
                serviceLog.WriteEntry("Запуск процедуры выгрузки накладных в формате IbsImport");
                string IBSConnectionString = Properties.Settings.Default.IBSConnectionString;  
                var path2IbsImport = Properties.Settings.Default.path2IbsImport;
                if (!Directory.Exists(path2IbsImport))
                    Directory.CreateDirectory(path2IbsImport);

                var ibs = new IBS.IbsDataContext(IBSConnectionString);     

                var SaleOrderList = ibs.GetSaleOrders(IBS.IMPORTTYPE.IbsImport);

                foreach (var saleOrder in SaleOrderList)
                {
                    try
                    {
                        var ibsImportData = ibs.GetIBSImport(saleOrder.INVOICE_ID);
                        Impersonation.Logon("sqladmin", "MOS", "12345678");
                        foreach (var line in ibsImportData)
                        {
                            if (!Directory.Exists(path2IbsImport + @"\" + line.SITEIBSCODE))
                                Directory.CreateDirectory(path2IbsImport + @"\" + line.SITEIBSCODE);
                            line.SerializeToFile(path2IbsImport + @"\" + line.SITEIBSCODE + @"\" + line.COMPANY_KEY + "_" + line.DOC_NUMBER + "_" + line.DOC_DATE.ToString("yyyy.MM.dd") + ".txt");
                        }
                        Impersonation.Logoff();
                        ibs.UpdateStatus(saleOrder.INVOICE_ID);
                    }
                    catch (Exception ex)
                    {
                        serviceLog.WriteEntry(String.Format("Ошибка при записи файла:\nMessage = '{0}'\nInnerException = '{1}'\nSource = '{2}'\n", ex.Message, ex.InnerException, ex.Source), EventLogEntryType.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                serviceLog.WriteEntry(String.Format("В процедуре формирования файла IbsImport произошла ошибка:\nMessage = '{0}'\nInnerException = '{1}'\nSource = '{2}'\n", ex.Message, ex.InnerException, ex.Source), EventLogEntryType.Error);
            }
        }
    }
}
